package cn.xuqiudong.demo.mvc.i18n;

import cn.xuqiudong.demo.mvc.i18n.helper.I18nHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.annotation.Resource;
import java.util.Locale;

/**
 * 说明:I18n 配置
 *
 * @author Vic.xu
 * @since 2023/4/19/0019 11:46
 */
@Configuration
public class I18nConfig implements WebMvcConfigurer, ApplicationRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(I18nConfig.class);


    @Resource
    private MessageSource messageSource;

    /**
     * 国际化change拦截器，参数为 locale
     * @param registry InterceptorRegistry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //默认的国际化参数为:locale
        LocaleChangeInterceptor interceptor =new LocaleChangeInterceptor();
        interceptor.setParamName("lang");
        registry.addInterceptor(interceptor);
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    /**
     *
     * 基于session的国际化 解析器
     */
    @Bean
    public LocaleResolver localeResolver(){
        LOGGER.info("registry LocaleResolver");
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        //Locale.US
        resolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return resolver;
    }

    /**
     * 不再把静态工具类I18nHelper 注入到spring，而是直接初始化其属性
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        I18nHelper.initI18nHelper(messageSource, localeResolver());
    }
}
